package com.shenganyuan.smac.worklog;

import android.annotation.SuppressLint;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps2d.model.LatLng;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.oklib.utils.assist.DateUtil;
import com.oklib.utils.helper.RxUtil;
import com.oklib.utils.network.http.ViseHttp;
import com.oklib.utils.network.http.callback.ACallback;
import com.oklib.utils.network.http.subscriber.ApiCallbackSubscriber;
import com.oklib.utils.network.loader.ILoader;
import com.oklib.utils.network.loader.LoaderManager;
import com.oklib.utils.view.SnackbarUtil;
import com.oklib.widget.recyclerview.BaseQuickAdapter;
import com.oklib.widget.recyclerview.BaseViewHolder;
import com.shenganyuan.smac.App;
import com.shenganyuan.smac.R;
import com.shenganyuan.smac.common.BaseActivity;
import com.shenganyuan.smac.common.beans.ApiCheckData;
import com.shenganyuan.smac.common.beans.ApiWorkLog;
import com.shenganyuan.smac.common.beans.ApiWorkLogSecond;
import com.shenganyuan.smac.common.beans.BeanCheckRecord;
import com.shenganyuan.smac.common.beans.BeanLeave;
import com.shenganyuan.smac.common.beans.BeanSign;
import com.shenganyuan.smac.common.beans.BeanWorkLogSecond;
import com.shenganyuan.smac.common.beans.User;
import com.shenganyuan.smac.common.data.Api;
import com.shenganyuan.smac.common.utils.DataConverter;
import com.shenganyuan.smac.common.view.RecyclerViewItemDivider;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * @author Damon
 */
public class ActWorkLog extends BaseActivity implements CalendarView.OnDateSelectedListener, CalendarView.OnYearChangeListener, CalendarView.OnMonthChangeListener {

    TextView mTextMonthDay;
    TextView mTextYear;
    TextView mTextLunar;
    TextView mTextCurrentDay;
    CalendarView mCalendarView;
    RelativeLayout mRelativeTool;
    private int mYear;
    CalendarLayout mCalendarLayout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    BaseQuickAdapter baseQuickAdapter = null;

    @Override
    public int getLayoutId() {
        return R.layout.act_work_log;
    }

    @Override
    public void initUI(Bundle savedInstanceState) {
        mTextMonthDay = findViewById(R.id.tv_month_day);
        mTextYear = findViewById(R.id.tv_year);
        mTextLunar = findViewById(R.id.tv_lunar);
        mRelativeTool = findViewById(R.id.rl_tool);
        mCalendarView = findViewById(R.id.calendarView);
        mTextCurrentDay = findViewById(R.id.tv_current_day);
        mTextMonthDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mCalendarLayout.isExpand()) {
                    mCalendarView.showYearSelectLayout(mYear);
                    return;
                }
                mCalendarView.showYearSelectLayout(mYear);
                mTextLunar.setVisibility(View.GONE);
                mTextYear.setVisibility(View.GONE);
                mTextMonthDay.setText(String.valueOf(mYear));
            }
        });
        findViewById(R.id.fl_current).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCalendarView.scrollToCurrent();
            }
        });
        mCalendarLayout = findViewById(R.id.calendarLayout);
        mCalendarView.setOnDateSelectedListener(this);
        mCalendarView.setOnYearChangeListener(this);
        mCalendarView.setOnMonthChangeListener(this);
        mTextYear.setText(String.valueOf(mCalendarView.getCurYear()));
        mYear = mCalendarView.getCurYear();
        mTextMonthDay.setText(mCalendarView.getCurMonth() + "月" + mCalendarView.getCurDay() + "日");
        mTextLunar.setText("今日");
        mTextCurrentDay.setText(String.valueOf(mCalendarView.getCurDay()));


    }

    @Override
    public void initData() {
        setTitle("施工日志");
        String dateStr = DateUtil.getStringByFormat(new Date(), new SimpleDateFormat("yyyyMM"));
        getServerData(dateStr);

        baseQuickAdapter = new BaseQuickAdapter<BeanWorkLogSecond, BaseViewHolder>(R.layout.act_log_item) {
            @Override
            protected void convert(BaseViewHolder helper, BeanWorkLogSecond item) {
                helper.setText(R.id.tv_title, item.getTitle());
                helper.setText(R.id.tv_log_type, DataConverter.getLogType(item));
                helper.setText(R.id.tv_desc, item.getDesc());
                helper.setText(R.id.tv_zq, item.getZq());
                helper.setText(R.id.tv_time, DataConverter.getDateStr(item.getTime()));
                TextView textView = helper.getView(R.id.tv_log_type);
                GradientDrawable mm = (GradientDrawable) textView.getBackground();
                mm.setColor(getResources().getColor(DataConverter.getLogTypeBgColor(item)));
                //本地图片
                if (item.getType() == BeanWorkLogSecond.TYPE_LEAVE) {
                    LoaderManager.getLoader().loadResource(helper.getView(R.id.img), R.drawable.icon_leave, new ILoader.Options(R.drawable.lib_img_default, R.drawable.lib_img_default));
                } else if (item.getType() == BeanWorkLogSecond.TYPE_SIGN) {
                    LoaderManager.getLoader().loadResource(helper.getView(R.id.img), R.drawable.icon_sign, new ILoader.Options(R.drawable.lib_img_default, R.drawable.lib_img_default));
                } else {
                    LoaderManager.getLoader().loadNet(helper.getView(R.id.img), item.getImgUrl(), new ILoader.Options(R.drawable.lib_img_default, R.drawable.lib_img_default));
                }
                helper.getView(R.id.tv_title).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String gps = item.getGps();
                        LatLng latLng = DataConverter.fromStrToLatLng(gps);
                        if (latLng == null) {
                            SnackbarUtil.show(getWindow().getDecorView(), "不可用的定位数据");
                            return;
                        }
                        DataConverter.openSdkMap(mContext, latLng.latitude, latLng.longitude);
                    }
                });
            }
        };
        mRecyclerView.addItemDecoration(new RecyclerViewItemDivider(mContext, LinearLayoutManager.VERTICAL)
                .setAppearance(20, "#eeeeee"));
        mRecyclerView.setAdapter(baseQuickAdapter);

    }

    /**
     * 处理数据
     *
     * @param apiWorkLog
     */
    private List<Calendar> operateData(ApiWorkLog apiWorkLog) {
        List<Calendar> schemes = new ArrayList<>();
        if (apiWorkLog == null) {
            return schemes;
        }
        List<ApiCheckData> checkDataList = apiWorkLog.getXcxxdate();
        List<BeanLeave> apiLeaves = apiWorkLog.getLeave();

        if (checkDataList != null) {
            for (int i = 0; i < checkDataList.size(); i++) {
                String dateStr = checkDataList.get(i).getXcxxdate();
                if (dateStr == null || dateStr.length() != 8) {
                    continue;
                }
                String txt = checkDataList.get(i).getNum();
                Calendar calendar = getSchemeCalendar(Integer.valueOf(dateStr.substring(0, 4)), Integer.valueOf(dateStr.substring(4, 6)), Integer.valueOf(dateStr.substring(6, 8)),
                        getResources().getColor(R.color.color_work_log_xcxx), txt);
                schemes.add(calendar);
            }
        }
        if (apiLeaves != null) {
            for (int i = 0; i < apiLeaves.size(); i++) {
                String dateStr = apiLeaves.get(i).getQjdate();
                if (dateStr == null || dateStr.length() != 8) {
                    continue;
                }
                Calendar calendar = getSchemeCalendar(Integer.valueOf(dateStr.substring(0, 4)), Integer.valueOf(dateStr.substring(4, 6)), Integer.valueOf(dateStr.substring(6, 8)),
                        getResources().getColor(R.color.color_work_log_leave), "假");
                schemes.add(calendar);
            }
        }
        return schemes;
    }

    private Calendar getSchemeCalendar(int year, int month, int day, int color, String text) {
        Calendar calendar = new Calendar();
        calendar.setYear(year);
        calendar.setMonth(month);
        calendar.setDay(day);
        calendar.setSchemeColor(color);//如果单独标记颜色、则会使用这个颜色
        calendar.setScheme(text);
        return calendar;
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void onDateSelected(Calendar calendar, boolean isClick) {
        mTextLunar.setVisibility(View.VISIBLE);
        mTextYear.setVisibility(View.VISIBLE);
        mTextMonthDay.setText(calendar.getMonth() + "月" + calendar.getDay() + "日");
        mTextYear.setText(String.valueOf(calendar.getYear()));
        mTextLunar.setText(calendar.getLunar());
        mYear = calendar.getYear();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(calendar.getYear() + "");
        if (calendar.getMonth() < 10) {
            stringBuffer.append("0");
            stringBuffer.append(calendar.getMonth());
        } else {
            stringBuffer.append(calendar.getMonth() + "");
        }
        if (calendar.getDay() < 10) {
            stringBuffer.append("0");
            stringBuffer.append(calendar.getDay());
        } else {
            stringBuffer.append(calendar.getDay() + "");
        }
        getServerDataByDate(stringBuffer.toString());
    }


    @Override
    public void onYearChange(int year) {
        mTextMonthDay.setText(String.valueOf(year));
    }

    /**
     * 获取施工日志信息-201804
     */
    private void getServerData(String dateStr) {
        if (TextUtils.isEmpty(dateStr)) {
            return;
        }
        User user = App.getCurrentUser();
        ViseHttp.RETROFIT().create(Api.class).getWorkLogs(user.getId(), dateStr, App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper()).subscribe(new ApiCallbackSubscriber<>(new ACallback<ApiWorkLog>() {
            @Override
            public void onSuccess(ApiWorkLog data) {
                try {
                    if ("true".equalsIgnoreCase(data.getResult())) {
                        List<Calendar> calendars = operateData(data);
                        mCalendarView.setSchemeDate(calendars);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                SnackbarUtil.showShort(getWindow().getDecorView(), "获取工作日志信息失败");
            }
        }));
    }

    /**
     * 获取某个日期的信息20180420
     */
    private void getServerDataByDate(String dateStr) {
        if (TextUtils.isEmpty(dateStr)) {
            return;
        }
        User user = App.getCurrentUser();
        ViseHttp.RETROFIT().create(Api.class).getWorkLogsSecond(user.getId(), dateStr, App.getAccessToken())
                .compose(RxUtil.rxSchedulerHelper()).subscribe(new ApiCallbackSubscriber<>(new ACallback<ApiWorkLogSecond>() {
            @Override
            public void onSuccess(ApiWorkLogSecond data) {
                try {
                    if ("true".equalsIgnoreCase(data.getResult())) {
                        baseQuickAdapter.setNewData(opearteDataSecond(data));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                SnackbarUtil.showShort(getWindow().getDecorView(), "获取日志信息失败");
            }
        }));
    }

    /**
     * 处理二级页面数据
     *
     * @param data
     */
    private List<BeanWorkLogSecond> opearteDataSecond(ApiWorkLogSecond data) {
        List<BeanWorkLogSecond> list = new ArrayList<>();
        BeanWorkLogSecond beanWorkLogSecond = null;
        List<BeanLeave> beanLeaves = data.getLeave();

        if (beanLeaves != null && beanLeaves.size() > 0) {
            for (int i = 0; i < beanLeaves.size(); i++) {
                BeanLeave beanLeave = beanLeaves.get(i);
                if (beanLeave != null) {
                    beanWorkLogSecond = new BeanWorkLogSecond();
                    beanWorkLogSecond.setId(beanLeave.getId());
                    beanWorkLogSecond.setDesc(beanLeave.getYuanyin());
                    beanWorkLogSecond.setTime(beanLeave.getQjdate());
                    beanWorkLogSecond.setTitle("请假");
                    beanWorkLogSecond.setType(BeanWorkLogSecond.TYPE_LEAVE);
                    beanWorkLogSecond.setGps(beanLeave.getGps());
                    list.add(beanWorkLogSecond);
                }
            }
        }

        List<BeanSign> beanSigns = data.getSign();
        if (beanSigns != null && beanSigns.size() > 0) {
            for (int i = 0; i < beanSigns.size(); i++) {
                BeanSign beanSign = beanSigns.get(i);
                if (beanSign != null) {
                    beanWorkLogSecond = new BeanWorkLogSecond();
                    beanWorkLogSecond.setId(beanSign.getId());
                    beanWorkLogSecond.setDesc("");
                    beanWorkLogSecond.setTime(beanSign.getQdTime());
                    beanWorkLogSecond.setTitle("签到");
                    beanWorkLogSecond.setGps(beanSign.getGps());
                    beanWorkLogSecond.setType(BeanWorkLogSecond.TYPE_SIGN);
                    list.add(beanWorkLogSecond);
                }
            }
        }

        List<BeanCheckRecord> beanCheckRecords = data.getXcxx();
        if (beanCheckRecords != null && beanCheckRecords.size() > 0) {
            for (int i = 0; i < beanCheckRecords.size(); i++) {
                BeanCheckRecord beanCheckRecord = beanCheckRecords.get(i);
                beanWorkLogSecond = new BeanWorkLogSecond();
                beanWorkLogSecond.setId(beanCheckRecord.getId());
                beanWorkLogSecond.setDesc(beanCheckRecord.getXcjl());
                beanWorkLogSecond.setTime(beanCheckRecord.getLrTime());
                beanWorkLogSecond.setTitle(beanCheckRecord.getGkZydyName());
                beanWorkLogSecond.setGps(beanCheckRecord.getGps());
                beanWorkLogSecond.setZq(beanCheckRecord.getZq());
                List<String> listImg = DataConverter.fromImgStrsToImg(beanCheckRecord.getXczp());
                if (listImg.size() > 0) {
                    beanWorkLogSecond.setImgUrl(listImg.get(0));
                }
                beanWorkLogSecond.setType(BeanWorkLogSecond.TYPE_XCXX);
                list.add(beanWorkLogSecond);
            }
        }
        return list;
    }

    @Override
    public void onMonthChange(int year, int month) {
        String dateStr = year + (month < 10 ? "0" + month : "" + month);
        getServerData(dateStr);
    }
}
